package user;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.concurrent.*;

/**
 * @program: SpringBootDemos
 * @description: 异步线程
 * @author: Kangsen
 * @create: 2022-05-24 09:18
 **/
@Slf4j
public class AsyncThread {

    @Test
    public void testFuture() throws InterruptedException, ExecutionException {
        //创建一个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        Task task = new Task();
        Task2 task2 = new Task2();
        //task提交给线程池
        Future submit = executorService.submit(task);
        Future submit1 = executorService.submit(task2);
        Future<?> submit2 = executorService.submit(new ThreadTest());
        Future<?> submit3 = executorService.submit(new ThreadTest2());
        Future<?> submit4 = executorService.submit(new Thread(()->{
            log.info("lambda执行开始");
            try {
                TimeUnit.SECONDS.sleep(2);
                log.info("lambda 执行结束");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }));

        Future<?> submit5 = executorService.submit(()-> {
            log.info("submit5执行开始");
            try {
                TimeUnit.SECONDS.sleep(2);
                log.info("submit5 执行结束");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        executorService.shutdown();
        log.info("线程池运行  主线程执行");
        //Object sum = submit.get();
        //log.info("主线程sum:{}",sum);
        //Object sum1 = submit1.get();
        //log.info("主线程sum1:{}",sum1);
        //log.info("submit4:{}",submit4);
    }
    class ThreadTest implements Runnable{
        @Override
        public void run() {
            log.info("子线程T开始执行");
            int sum = 0;
            for (int i = 0; i < 1000; i++) {
                sum += i;
            }
            log.info("子线程T执行完：{}",sum);
        }
    }

    class ThreadTest2 extends Thread{
        @Override
        public void run() {
            log.info("子线程T2开始执行");
            int sum = 0;
            for (int i = 0; i < 1000; i++) {
                sum += i;
            }
            log.info("子线程T2执行完：{}",sum);
        }
    }

    class Task implements Callable{
        @Override
        public Integer call() throws Exception {
            log.info("子线程1开始执行");
            int sum = 0;
            for (int i = 0; i < 1000; i++) {
                sum += i;
            }
            log.info("子线程1执行完：{}",sum);
            return sum;
        }
    }

    class Task2 implements Callable{
        @Override
        public Object call() throws Exception {
            log.info("子线程2开始执行");
            int sum = 0;
            for (int i = 0; i < 1000; i++) {
                sum += i;
            }
            log.info("子线程2执行完：{}",sum);
            return sum;
        }
    }

}
